package com.miyake.client.community;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.miyake.client.DataService;
import com.miyake.client.DataServiceAsync;
import com.miyake.client.datamanage.Paper;
import com.miyake.client.tools.ClickableLabel;

public class PaperList extends Composite {
	interface PaperListHandler {
		void onPaperSelect(String key);
	}
	private List<PaperListHandler> handlers = new ArrayList<PaperListHandler>();
	public void addPalerListHandler(PaperListHandler handler) {
		handlers.add(handler);
	}
	protected void fireSelectEvent(String key) {
		for (PaperListHandler handler : handlers) {
			handler.onPaperSelect(key);
		}
	}
	private DataServiceAsync service = DataService.Util.getInstance();
	
	public PaperList() {
		VerticalPanel verticalPanel = new VerticalPanel();
		initWidget(verticalPanel);
		verticalPanel.setWidth("100%");
		verticalPanel.add(new HTML("<h2>Posted Papers</h2>"));
		Grid grid = new Grid(1, 1);
		grid.setBorderWidth(1);
		grid.setWidth("100%");
		verticalPanel.add(grid);
		
		getRowData(grid);

	}
	private void getRowData(final Grid grid) {
		service.getPaperList("", new AsyncCallback<List<Paper>>() {
			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(List<Paper> result) {
				grid.resize(result.size()+1, 3);
				grid.setHTML(0, 1, "<b>Title</b>");
				grid.setHTML(0, 2, "<b>Author</b>");
				int row = 1;
				for (final Paper paper : result) {
					grid.setText(row, 0, String.valueOf(row));
					Label title = new ClickableLabel(paper.getTitle());
					title.addClickHandler(new ClickHandler() {
						@Override
						public void onClick(ClickEvent event) {
							fireSelectEvent(paper.getNodeKey());
						}
					});
					grid.setWidget(row, 1, title);
					grid.setWidget(row, 2, new ClickableLabel(paper.getAuthor()));
					row++;
				}
			}
			
		});
	}
}
